using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FPWeapon : MonoBehaviour
{
    public float FireRate;

    public GameObject BulletPrefab;
    public Transform Muzzle;

    public float BulletSpeed = 10;
    public Animator ArmAnimator;
    public Animator GunAnimator;

    private float lastFireTime;
    private bool isAiming;
    private WindManager_Tutorial windManager;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
        windManager = FindObjectOfType<WindManager_Tutorial>();
    }

    // Update is called once per frame
    void Update()
    {
        HandleAiming();
        HandleFire();
    }

    private void HandleAiming()
    {
        if (Input.GetMouseButtonDown(1))
        {
            isAiming = true;
        }

        if (Input.GetMouseButtonUp(1))
        {
            isAiming = false;
        }

        ArmAnimator.SetBool("Aiming", isAiming);
    }

    private void HandleFire()
    {
        //Handle Fire
        if (!Input.GetMouseButtonDown(0) || !AllowFire()) return;
        GunAnimator.SetTrigger("Shoot");


        var tmp_BulletClone = Instantiate(BulletPrefab, Muzzle.position, Muzzle.rotation);
        var tmp_BulletMoverScript = tmp_BulletClone.AddComponent<FPBulletMover_Tutorial>();
        tmp_BulletMoverScript.Initialization(Muzzle,BulletSpeed,windManager);

        //Delete bullet after 10s
        Destroy(tmp_BulletClone, 50);

        //Reset fire time
        lastFireTime = Time.time;
    }


    bool AllowFire()
    {
        return Time.time - lastFireTime > 1 / FireRate;
    }
}